<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">


<meta name="google-site-verification" content="E9deYnivN5MuHMuIfiMZZfS0alv-d_0UjcwjBL79lGU" />



<meta name="baidu-site-verification" content="iHYWJxscwD" />










<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="true" />








  <meta name="baidu-site-verification" content="true" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Python,学习笔记,量化投资,回测指标,Backtrader,empyrical," />










<meta name="description" content="使用backtrader计算α，β，信息比例等回测指标。参考：https:&#x2F;&#x2F;www.r-bloggers.com&#x2F;stock-trading-analytics-and-optimization-in-python-with-pyfolio-rs-performanceanalytics-and-backtrader&#x2F;https:&#x2F;&#x2F;teddykoker.com&#x2F;2019&#x2F;05&#x2F;improvin">
<meta property="og:type" content="article">
<meta property="og:title" content="量化投资学习笔记80——实现量化交易经典策略:计算回测指标">
<meta property="og:url" content="https://zwdnet.github.io/2020/07/27/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B080%E2%80%94%E2%80%94%E5%AE%9E%E7%8E%B0%E9%87%8F%E5%8C%96%E4%BA%A4%E6%98%93%E7%BB%8F%E5%85%B8%E7%AD%96%E7%95%A5-%E8%AE%A1%E7%AE%97%E5%9B%9E%E6%B5%8B%E6%8C%87%E6%A0%87/index.html">
<meta property="og:site_name" content="赵瑜敏的口腔医学专业学习博客">
<meta property="og:description" content="使用backtrader计算α，β，信息比例等回测指标。参考：https:&#x2F;&#x2F;www.r-bloggers.com&#x2F;stock-trading-analytics-and-optimization-in-python-with-pyfolio-rs-performanceanalytics-and-backtrader&#x2F;https:&#x2F;&#x2F;teddykoker.com&#x2F;2019&#x2F;05&#x2F;improvin">
<meta property="og:locale">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/53/01.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/53/02.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/53/03.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/53/04.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/53/05.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/53/06.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/53/07.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/53/08.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/53/09.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/53/10.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg">
<meta property="article:published_time" content="2020-07-27T07:51:58.000Z">
<meta property="article:modified_time" content="2020-08-30T05:52:04.000Z">
<meta property="article:author" content="赵瑜敏">
<meta property="article:tag" content="Python">
<meta property="article:tag" content="学习笔记">
<meta property="article:tag" content="量化投资">
<meta property="article:tag" content="回测指标">
<meta property="article:tag" content="Backtrader">
<meta property="article:tag" content="empyrical">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/53/01.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zwdnet.github.io/2020/07/27/量化投资学习笔记80——实现量化交易经典策略-计算回测指标/"/>





  <title>量化投资学习笔记80——实现量化交易经典策略:计算回测指标 | 赵瑜敏的口腔医学专业学习博客</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">赵瑜敏的口腔医学专业学习博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zwdnet.github.io/2020/07/27/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B080%E2%80%94%E2%80%94%E5%AE%9E%E7%8E%B0%E9%87%8F%E5%8C%96%E4%BA%A4%E6%98%93%E7%BB%8F%E5%85%B8%E7%AD%96%E7%95%A5-%E8%AE%A1%E7%AE%97%E5%9B%9E%E6%B5%8B%E6%8C%87%E6%A0%87/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="赵瑜敏的口腔医学专业学习博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">量化投资学习笔记80——实现量化交易经典策略:计算回测指标</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-07-27T07:51:58+00:00">
                2020-07-27
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" itemprop="url" rel="index">
                    <span itemprop="name">量化投资</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                  <span class="post-meta-divider">|</span>
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2.5k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  11
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>使用backtrader计算α，β，信息比例等回测指标。<br>参考：<br><a target="_blank" rel="noopener" href="https://www.r-bloggers.com/stock-trading-analytics-and-optimization-in-python-with-pyfolio-rs-performanceanalytics-and-backtrader/">https://www.r-bloggers.com/stock-trading-analytics-and-optimization-in-python-with-pyfolio-rs-performanceanalytics-and-backtrader/</a><br><a target="_blank" rel="noopener" href="https://teddykoker.com/2019/05/improving-cross-sectional-mean-reversion-strategy-in-python/">https://teddykoker.com/2019/05/improving-cross-sectional-mean-reversion-strategy-in-python/</a><br>对于框架没有的指标，可以自建分析类，继承自backtrader.Analyzer，实现next()和stop()函数来计算指标，get_analysis()来获取分析结果。然后用addanalyzer()方法将分析类加载到cerebro对象里，这是一种轻量的做法，不需要在分析类里提供数据。<br>上面文章的作者是调用用R的PerformanceAnalytics库计算指标，我这没成功，搜了一下，用另一个python库，empyreal吧。<br>使用empyreal需要两个收益率序列，分别是策略的收益率和基准的收益率，这里的收益率是当前交易日相对前一交易日的收益率。对于策略收益率，可以向cerebro里添加TimeReturn分析器获得。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">self.__cerebro.addanalyzer(btay.TimeReturn, _name = <span class="string">&quot;TR&quot;</span>)</span><br></pre></td></tr></table></figure>
<p>在运行了回测以后获得策略收益率序列:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">self.__returns = pd.Series(self.__results[<span class="number">0</span>].analyzers.TR.get_analysis())</span><br></pre></td></tr></table></figure>
<p>基准策略的收益率序列呢？再建一个策略类吧。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 基准策略类，用于计算α，β等回测指标</span></span><br><span class="line"><span class="comment"># 采用第一天全仓买入并持有的策略</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Benchmark</span>(<span class="params">bt.Strategy</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.order = <span class="literal">None</span></span><br><span class="line">        self.bBuy = <span class="literal">False</span></span><br><span class="line">        self.dataclose = self.datas[<span class="number">0</span>].close</span><br><span class="line">       </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">next</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">if</span> self.bBuy == <span class="literal">True</span>:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            cash = self.broker.get_cash()</span><br><span class="line">            stock = math.ceil(cash/self.dataclose/<span class="number">100</span>)*<span class="number">100</span> - <span class="number">100</span></span><br><span class="line">            self.order = self.buy(size = stock, price = self.datas[<span class="number">0</span>].close)</span><br><span class="line">            self.bBuy = <span class="literal">True</span></span><br><span class="line">           </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">stop</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.order = self.close()</span><br></pre></td></tr></table></figure>
<p>再用前述方法计算收益率序列。<br>接着自己定义一个risk分析类。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> empyrical <span class="keyword">as</span> ey</span><br><span class="line"><span class="comment"># 用empyrical库计算风险指标</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">riskAnalyzer</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, returns, benchReturns, riskFreeRate = <span class="number">0.02</span></span>):</span></span><br><span class="line">        self.__returns = returns</span><br><span class="line">        self.__benchReturns = benchReturns</span><br><span class="line">        self.__risk_free = riskFreeRate</span><br><span class="line">        self.__alpha = <span class="number">0.0</span></span><br><span class="line">        self.__beta = <span class="number">0.0</span></span><br><span class="line">        self.__info = <span class="number">0.0</span></span><br><span class="line">        self.__vola = <span class="number">0.0</span></span><br><span class="line">        self.__omega = <span class="number">0.0</span></span><br><span class="line">        self.__sharpe = <span class="number">0.0</span></span><br><span class="line">        self.__sortino = <span class="number">0.0</span></span><br><span class="line">        self.__calmar = <span class="number">0.0</span></span><br><span class="line">       </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">run</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="comment"># 计算各指标</span></span><br><span class="line">        self._alpha()</span><br><span class="line">        self._beta()</span><br><span class="line">        self._info()</span><br><span class="line">        self._vola()</span><br><span class="line">        self._omega()</span><br><span class="line">        self._sharpe()</span><br><span class="line">        self._sortino()</span><br><span class="line">        result = pd.Series()</span><br><span class="line">        result[<span class="string">&quot;阿尔法&quot;</span>] = self.__alpha</span><br><span class="line">        result[<span class="string">&quot;贝塔&quot;</span>] = self.__beta</span><br><span class="line">        result[<span class="string">&quot;信息比例&quot;</span>] = self.__info</span><br><span class="line">        result[<span class="string">&quot;策略波动率&quot;</span>] = self.__vola</span><br><span class="line">        result[<span class="string">&quot;欧米伽&quot;</span>] = self.__omega</span><br><span class="line">        result[<span class="string">&quot;夏普值&quot;</span>] = self.__sharpe</span><br><span class="line">        result[<span class="string">&quot;sortino&quot;</span>] = self.__sortino</span><br><span class="line">        result[<span class="string">&quot;calmar&quot;</span>] = self.__calmar</span><br><span class="line">        <span class="keyword">return</span> result</span><br><span class="line">       </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">_alpha</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.__alpha = ey.alpha(returns = self.__returns, factor_returns = self.__benchReturns, risk_free = self.__risk_free)</span><br><span class="line">       </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">_beta</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.__beta = ey.beta(returns = self.__returns, factor_returns = self.__benchReturns, risk_free = self.__risk_free)</span><br><span class="line">       </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">_info</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.__info = ey.excess_sharpe(returns = self.__returns, factor_returns = self.__benchReturns)</span><br><span class="line">       </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">_vola</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.__vola = ey.annual_volatility(self.__returns, period=<span class="string">&#x27;daily&#x27;</span>)</span><br><span class="line">   </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">_omega</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.__omega = ey.omega_ratio(returns = self.__returns, risk_free = self.__risk_free)</span><br><span class="line">       </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">_sharpe</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.__sharpe = ey.sharpe_ratio(returns = self.__returns)</span><br><span class="line">       </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">_sortino</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.__sortino = ey.sortino_ratio(returns = self.__returns)</span><br><span class="line">       </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">_calmar</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.__calmar = ey.calmar_ratio(returns = self.__returns)</span><br><span class="line">在BackTest里增加一个风险分析函数:</span><br><span class="line">    <span class="comment"># 分析策略的风险指标</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">_riskAnaly</span>(<span class="params">self</span>):</span></span><br><span class="line">        risk = riskAnalyzer(self.__returns, self.__benchReturns)</span><br><span class="line">        result = risk.run()</span><br><span class="line">        self.__backtestResult[<span class="string">&quot;阿尔法&quot;</span>] = result[<span class="string">&quot;阿尔法&quot;</span>]</span><br><span class="line">        self.__backtestResult[<span class="string">&quot;贝塔&quot;</span>] = result[<span class="string">&quot;贝塔&quot;</span>]</span><br><span class="line">        self.__backtestResult[<span class="string">&quot;信息比例&quot;</span>] = result[<span class="string">&quot;信息比例&quot;</span>]</span><br><span class="line">        self.__backtestResult[<span class="string">&quot;策略波动率&quot;</span>] = result[<span class="string">&quot;策略波动率&quot;</span>]</span><br><span class="line">        self.__backtestResult[<span class="string">&quot;欧米伽&quot;</span>] = result[<span class="string">&quot;欧米伽&quot;</span>]</span><br><span class="line">        self.__backtestResult[<span class="string">&quot;夏普值&quot;</span>] = result[<span class="string">&quot;夏普值&quot;</span>]</span><br><span class="line">        self.__backtestResult[<span class="string">&quot;sortino&quot;</span>] = result[<span class="string">&quot;sortino&quot;</span>]</span><br><span class="line">        self.__backtestResult[<span class="string">&quot;calmar&quot;</span>] = result[<span class="string">&quot;calmar&quot;</span>]</span><br></pre></td></tr></table></figure>
<p>运行<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/53/01.png"><br>OK，有点问题，夏普值Backtrader和empyrical的计算结果有差异，可能参数设置有差异吧。调试一下看看。<br>用这篇文章 <a target="_blank" rel="noopener" href="https://www.cnblogs.com/bitquant/p/8432891.html">https://www.cnblogs.com/bitquant/p/8432891.html</a> 的数据和例子，用我的程序计算。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    <span class="comment"># 构造测试数据</span></span><br><span class="line">    returns = pd.Series(</span><br><span class="line">        index = pd.date_range(<span class="string">&quot;2017-03-10&quot;</span>, <span class="string">&quot;2017-03-19&quot;</span>),</span><br><span class="line">        data = (-<span class="number">0.012143</span>, <span class="number">0.045350</span>, <span class="number">0.030957</span>, <span class="number">0.004902</span>, <span class="number">0.002341</span>, -<span class="number">0.02103</span>, <span class="number">0.00148</span>, <span class="number">0.004820</span>, -<span class="number">0.00023</span>, <span class="number">0.01201</span>))</span><br><span class="line">    print(returns)</span><br><span class="line">    benchmark_returns = pd.Series(</span><br><span class="line">        index = pd.date_range(<span class="string">&quot;2017-03-10&quot;</span>, <span class="string">&quot;2017-03-19&quot;</span>),</span><br><span class="line">        data = ( -<span class="number">0.031940</span>, <span class="number">0.025350</span>, -<span class="number">0.020957</span>, -<span class="number">0.000902</span>, <span class="number">0.007341</span>, -<span class="number">0.01103</span>, <span class="number">0.00248</span>, <span class="number">0.008820</span>, -<span class="number">0.00123</span>, <span class="number">0.01091</span>))</span><br><span class="line">    print(benchmark_returns)</span><br><span class="line">    <span class="comment"># 计算累积收益率</span></span><br><span class="line">    creturns = ey.cum_returns(returns)</span><br><span class="line">    print(<span class="string">&quot;累积收益率\n&quot;</span>, creturns)</span><br><span class="line">    risk = riskAnalyzer(returns, benchmark_returns, riskFreeRate = <span class="number">0.01</span>)</span><br><span class="line">    results = risk.run()</span><br><span class="line">    print(results)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/53/02.png"><br>大部分结果跟文章里是一致的，但是阿尔法值文章里是0.7781，Calmar比率为207.1054，这两个值不对。<br>直接调用empyreal算一下看看。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">    <span class="comment"># 直接调用empyrical试试</span></span><br><span class="line">    alpha = ey.alpha(returns = returns, factor_returns = benchmark_returns, risk_free = <span class="number">0.01</span>)</span><br><span class="line">    calmar = ey.calmar_ratio(returns)</span><br><span class="line">    print(alpha, calmar)</span><br><span class="line"><span class="number">1.1749273413863706</span> <span class="number">207.10543798664153</span></span><br></pre></td></tr></table></figure>
<p>阿尔法值还是不对，calmar值对了。先改计算calmar的程序。原来是我忘了调用我的类里面计算calmar的程序，加上去就对了。那么阿尔法值呢？<br>自己算一下:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">    <span class="comment"># 自己计算阿尔法值</span></span><br><span class="line">    annual_return = ey.annual_return(returns)</span><br><span class="line">    annual_bench = ey.annual_return(benchmark_returns)</span><br><span class="line">    print(annual_return, annual_bench)</span><br><span class="line">    alpha2 = (annual_return - <span class="number">0.01</span>) - results[<span class="string">&quot;贝塔&quot;</span>]*(annual_bench - <span class="number">0.01</span>)</span><br><span class="line">    print(alpha2)</span><br><span class="line"><span class="number">4.355427360859065</span> -<span class="number">0.26851705257114356</span></span><br><span class="line"><span class="number">4.501836011461441</span></span><br></pre></td></tr></table></figure>
<p>算出来4.5，差别更大了。换篇文章看看。<br><a target="_blank" rel="noopener" href="http://www.imooc.com/article/293203">http://www.imooc.com/article/293203</a></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 自己计算阿尔法贝塔</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get_return</span>(<span class="params">code, startdate, endate</span>):</span></span><br><span class="line">        df = ts.get_k_data(code, ktype = <span class="string">&quot;D&quot;</span>, autype = <span class="string">&quot;qfq&quot;</span>, start = startdate, end = endate)</span><br><span class="line">        p1 = np.array(df.close[<span class="number">1</span>:])</span><br><span class="line">        p0 = np.array(df.close[:-<span class="number">1</span>])</span><br><span class="line">        logret = np.log(p1/p0)</span><br><span class="line">        rate = pd.DataFrame()</span><br><span class="line">        rate[code] = logret</span><br><span class="line">        rate.index = df[<span class="string">&quot;date&quot;</span>][<span class="number">1</span>:]</span><br><span class="line">        <span class="keyword">return</span> rate</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">alpha_beta</span>(<span class="params">code, startdate, endate</span>):</span></span><br><span class="line">        mkt_ret = get_return(<span class="string">&quot;sh&quot;</span>, startdate, endate)</span><br><span class="line">        stock_ret = get_return(code, startdate, endate)</span><br><span class="line">        df = pd.merge(mkt_ret, stock_ret, left_index = <span class="literal">True</span>, right_index = <span class="literal">True</span>)</span><br><span class="line">        x = df.iloc[:, <span class="number">0</span>]</span><br><span class="line">        y = df.iloc[:, <span class="number">1</span>]</span><br><span class="line">        beta, alpha, r_value, p_value, std_err = stats.linregress(x, y)</span><br><span class="line">        <span class="keyword">return</span> (alpha, beta)</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">stocks_alpha_beta</span>(<span class="params">stocks, startdate, endate</span>):</span></span><br><span class="line">        df = pd.DataFrame()</span><br><span class="line">        alpha = []</span><br><span class="line">        beta = []</span><br><span class="line">        <span class="keyword">for</span> code <span class="keyword">in</span> stocks.values():</span><br><span class="line">            a, b = alpha_beta(code, startdate, endate)</span><br><span class="line">            alpha.append(<span class="built_in">float</span>(<span class="string">&quot;%.4f&quot;</span>%a))</span><br><span class="line">            beta.append(<span class="built_in">float</span>(<span class="string">&quot;%.4f&quot;</span>%b))</span><br><span class="line">        df[<span class="string">&quot;alpha&quot;</span>] = alpha</span><br><span class="line">        df[<span class="string">&quot;beta&quot;</span>] = beta</span><br><span class="line">        df.index = stocks.keys()</span><br><span class="line">        <span class="keyword">return</span> df</span><br><span class="line">       </span><br><span class="line">    startdate = <span class="string">&quot;2017-01-01&quot;</span></span><br><span class="line">    endate = <span class="string">&quot;2018-11-09&quot;</span></span><br><span class="line">    stocks=&#123;<span class="string">&#x27;中国平安&#x27;</span>:<span class="string">&#x27;601318&#x27;</span>,<span class="string">&#x27;格力电器&#x27;</span>:<span class="string">&#x27;000651&#x27;</span>,<span class="string">&#x27;招商银行&#x27;</span>:<span class="string">&#x27;600036&#x27;</span>,<span class="string">&#x27;恒生电子&#x27;</span>:<span class="string">&#x27;600570&#x27;</span>,<span class="string">&#x27;中信证券&#x27;</span>:<span class="string">&#x27;600030&#x27;</span>,<span class="string">&#x27;贵州茅台&#x27;</span>:<span class="string">&#x27;600519&#x27;</span>&#125;</span><br><span class="line">    results = stocks_alpha_beta(stocks, startdate, endate)</span><br><span class="line">    print(results)</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">计算结果</span><br><span class="line">alpha    beta</span><br><span class="line">中国平安  <span class="number">0.0020</span>  <span class="number">1.2701</span></span><br><span class="line">格力电器  <span class="number">0.0016</span>  <span class="number">1.2261</span></span><br><span class="line">招商银行  <span class="number">0.0016</span>  <span class="number">1.0667</span></span><br><span class="line">恒生电子  <span class="number">0.0007</span>  <span class="number">1.4698</span></span><br><span class="line">中信证券  <span class="number">0.0008</span>  <span class="number">1.3857</span></span><br><span class="line">贵州茅台  <span class="number">0.0017</span>  <span class="number">1.0937</span></span><br></pre></td></tr></table></figure>
<p>跟原文的结果一致。下面用empyreal算一下看看。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 用empyrical计算</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">stocks_alpha_beta2</span>(<span class="params">stocks, startdate, endate</span>):</span></span><br><span class="line">    df = pd.DataFrame()</span><br><span class="line">    alpha = []</span><br><span class="line">    beta = []</span><br><span class="line">    <span class="keyword">for</span> code <span class="keyword">in</span> stocks.values():</span><br><span class="line">        a, b = empyrical_alpha_beta(code, startdate, endate)</span><br><span class="line">        alpha.append(<span class="built_in">float</span>(<span class="string">&quot;%.4f&quot;</span>%a))</span><br><span class="line">        beta.append(<span class="built_in">float</span>(<span class="string">&quot;%.4f&quot;</span>%b))</span><br><span class="line">    df[<span class="string">&quot;alpha&quot;</span>] = alpha</span><br><span class="line">    df[<span class="string">&quot;beta&quot;</span>] = beta</span><br><span class="line">    df.index = stocks.keys()</span><br><span class="line">    <span class="keyword">return</span> df</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">empyrical_alpha_beta</span>(<span class="params">code, startdate, endate</span>):</span></span><br><span class="line">    mkt_ret = get_return(<span class="string">&quot;sh&quot;</span>, startdate, endate)</span><br><span class="line">    stock_ret = get_return(code, startdate, endate)</span><br><span class="line">    alpha, beta = ey.alpha_beta(returns = stock_ret, factor_returns = mkt_ret)</span><br><span class="line">    <span class="keyword">return</span> (alpha, beta)</span><br><span class="line">    </span><br><span class="line">results2 = stocks_alpha_beta2(stocks, startdate, endate)</span><br><span class="line">print(<span class="string">&quot;empyrical计算结果&quot;</span>)</span><br><span class="line">print(results2)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/53/03.png"><br>贝塔值是一样的，阿尔法值差别就大了。<br>除一下两组阿尔法值: </p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">print(results2[<span class="string">&quot;alpha&quot;</span>]/results[<span class="string">&quot;alpha&quot;</span>])</span><br><span class="line"></span><br><span class="line">中国平安 <span class="number">317.750000</span></span><br><span class="line">格力电器 <span class="number">306.375000</span></span><br><span class="line">招商银行 <span class="number">315.125000</span></span><br><span class="line">恒生电子 <span class="number">279.428571</span></span><br><span class="line">中信证券 <span class="number">269.750000</span></span><br><span class="line">贵州茅台 <span class="number">307.529412</span></span><br></pre></td></tr></table></figure>
<p>并不一致。<br>经过不断试验，发现是参数的问题:<br>annualization = 1就完全一样啦。这个参数是设置收益率是多长时间间隔的收益率，1代表每天的收益率。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alpha, beta = ey.alpha_beta(returns = stock_ret, factor_returns = mkt_ret, annualization = <span class="number">1</span>)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/53/04.png"><br>再回测一下双均线策略<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/53/05.png"><br>现在的问题就剩夏普值的计算了，这又是一个比较重要的数据。还是用一样的方法调试：自己实现一下计算夏普值，再跟empyrical计算的结果对比。<br>照这篇文章： <a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/61949367">https://zhuanlan.zhihu.com/p/61949367</a> 的方法来。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 测试夏普值的计算</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">testSharpe</span>():</span></span><br><span class="line">    <span class="comment"># 读取数据</span></span><br><span class="line">    stock_data = pd.read_csv(<span class="string">&quot;stock_data.csv&quot;</span>, parse_dates = [<span class="string">&quot;Date&quot;</span>], index_col = [<span class="string">&quot;Date&quot;</span>]).dropna()</span><br><span class="line">    benchmark_data = pd.read_csv(<span class="string">&quot;benchmark_data.csv&quot;</span>, parse_dates = [<span class="string">&quot;Date&quot;</span>], index_col = [<span class="string">&quot;Date&quot;</span>]).dropna()</span><br><span class="line">    <span class="comment"># 了解数据</span></span><br><span class="line">    print(<span class="string">&quot;Stocks\n&quot;</span>)</span><br><span class="line">    print(stock_data.info())</span><br><span class="line">    print(stock_data.head())</span><br><span class="line">    print(<span class="string">&quot;\nBenchmarks\n&quot;</span>)</span><br><span class="line">    print(benchmark_data.info())</span><br><span class="line">    print(benchmark_data.head())</span><br><span class="line">    <span class="comment"># 输出统计量</span></span><br><span class="line">    print(stock_data.describe())</span><br><span class="line">    print(benchmark_data.describe())</span><br><span class="line">    <span class="comment"># 计算每日回报率</span></span><br><span class="line">    stock_returns = stock_data.pct_change()</span><br><span class="line">    print(stock_returns.describe())</span><br><span class="line">    sp_returns = benchmark_data.pct_change()</span><br><span class="line">    print(sp_returns.describe())</span><br><span class="line">    <span class="comment"># 每日超额回报</span></span><br><span class="line">    excess_returns = pd.DataFrame()</span><br><span class="line">    excess_returns[<span class="string">&quot;Amazon&quot;</span>] = stock_returns[<span class="string">&quot;Amazon&quot;</span>] - sp_returns[<span class="string">&quot;S&amp;P 500&quot;</span>]</span><br><span class="line">    excess_returns[<span class="string">&quot;Facebook&quot;</span>] = stock_returns[<span class="string">&quot;Facebook&quot;</span>] - sp_returns[<span class="string">&quot;S&amp;P 500&quot;</span>]</span><br><span class="line">    print(excess_returns.describe())</span><br><span class="line">    <span class="comment"># 超额回报的均值</span></span><br><span class="line">    avg_excess_return = excess_returns.mean()</span><br><span class="line">    print(avg_excess_return)</span><br><span class="line">    <span class="comment"># 超额回报的标准差</span></span><br><span class="line">    std_excess_return = excess_returns.std()</span><br><span class="line">    print(std_excess_return)</span><br><span class="line">    <span class="comment"># 计算夏普比率</span></span><br><span class="line">    <span class="comment"># 日夏普比率</span></span><br><span class="line">    daily_sharpe_ratio = avg_excess_return.div(std_excess_return)</span><br><span class="line">    <span class="comment"># 年化夏普比率</span></span><br><span class="line">    annual_factor = np.sqrt(<span class="number">252</span>)</span><br><span class="line">    annual_sharpe_ratio = daily_sharpe_ratio.mul(annual_factor)</span><br><span class="line">    print(<span class="string">&quot;年化夏普比率\n&quot;</span>, annual_sharpe_ratio)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/53/06.png"><br>接下来再用empyrical算。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 用empyrical算</span></span><br><span class="line">sharpe = pd.DataFrame()</span><br><span class="line">a = ey.sharpe_ratio(stock_returns[<span class="string">&quot;Amazon&quot;</span>])</span><br><span class="line">b = ey.sharpe_ratio(stock_returns[<span class="string">&quot;Facebook&quot;</span>])</span><br><span class="line">print(<span class="string">&quot;empyrical计算结果&quot;</span>)</span><br><span class="line">print(a, b)</span><br><span class="line">print(a/annual_sharpe_ratio[<span class="string">&quot;Amazon&quot;</span>], b/annual_sharpe_ratio[<span class="string">&quot;Facebook&quot;</span>])</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/53/07.png"><br>结果还是不对。还是参数问题？改改试试。<br>把上面程序作为基准的标普500换成固定的年化4%，设定</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">risk_free = <span class="number">0.04</span>/<span class="number">252.0</span></span><br></pre></td></tr></table></figure>
<p>empyrical计算程序设定risk_free参数</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 用empyrical算</span></span><br><span class="line">sharpe = pd.DataFrame()</span><br><span class="line">a = ey.sharpe_ratio(stock_returns[<span class="string">&quot;Amazon&quot;</span>], risk_free = risk_free)<span class="comment">#, annualization = 252)</span></span><br><span class="line">b = ey.sharpe_ratio(stock_returns[<span class="string">&quot;Facebook&quot;</span>], risk_free = risk_free)</span><br><span class="line">print(<span class="string">&quot;empyrical计算结果&quot;</span>)</span><br><span class="line">print(a, b)</span><br><span class="line">print(a/annual_sharpe_ratio[<span class="string">&quot;Amazon&quot;</span>], b/annual_sharpe_ratio[<span class="string">&quot;Facebook&quot;</span>])</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/53/08.png"><br>这下对了!说明empyrical算的没问题(废话!)，现在来解决我回测中的计算夏普值差异的问题。<br>搜了一下backtrader的文档，例子里就有计算年化夏普值的程序，照着来吧:<br><a target="_blank" rel="noopener" href="https://www.backtrader.com/docu/analyzers/analyzers/">https://www.backtrader.com/docu/analyzers/analyzers/</a></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 计算年化夏普值，参考backtrader的文档</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SharpeRatio</span>(<span class="params">Analyzer</span>):</span></span><br><span class="line">    params = ((<span class="string">&quot;timeframe&quot;</span>, TimeFrame.Years), (<span class="string">&quot;riskfreerate&quot;</span>, <span class="number">0.02</span>))</span><br><span class="line">   </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="built_in">super</span>(SharpeRatio, self).__init__()</span><br><span class="line">        self.anret = AnnualReturn()</span><br><span class="line">       </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">start</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line">       </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">next</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line">       </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">stop</span>(<span class="params">self</span>):</span></span><br><span class="line">        retfree = [self.p.riskfreerate] * <span class="built_in">len</span>(self.anret.rets)</span><br><span class="line">        retavg = average(<span class="built_in">list</span>(<span class="built_in">map</span>(operator.sub, self.anret.rets, retfree)))</span><br><span class="line">        retdev = standarddev(self.anret.rets)</span><br><span class="line">       </span><br><span class="line">        self.ratio = retavg/retdev</span><br><span class="line">       </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get_analysis</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">dict</span>(sharperatio = self.ratio)</span><br></pre></td></tr></table></figure>
<p>输出结果<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/53/09.png"><br>还是一个不同于一个啊?再试试SharpeRatio_A分析器吧。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/53/10.png"><br>四个不同的结果……先用backtrader框架的数据吧。反正不同的策略对比用的是同一个计算方法。<br>代码地址还是： <a target="_blank" rel="noopener" href="https://github.com/zwdnet/MyQuant/tree/master/47">https://github.com/zwdnet/MyQuant/tree/master/47</a><br>主要修改了backtest.py文件。</p>
<p>我发文章的三个地方，欢迎大家在朋友圈等地方分享，欢迎点“在看”。<br>我的个人博客地址：<a href="https://zwdnet.github.io/">https://zwdnet.github.io</a><br>我的知乎文章地址： <a target="_blank" rel="noopener" href="https://www.zhihu.com/people/zhao-you-min/posts">https://www.zhihu.com/people/zhao-you-min/posts</a><br>我的微信个人订阅号：赵瑜敏的口腔医学学习园地</p>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg"></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欢迎打赏！感谢支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/mm_facetoface_collect_qrcode_1542944836634.png" alt=" 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/1542944857770.jpg" alt=" 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
            <a href="/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" rel="tag"># 学习笔记</a>
          
            <a href="/tags/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" rel="tag"># 量化投资</a>
          
            <a href="/tags/%E5%9B%9E%E6%B5%8B%E6%8C%87%E6%A0%87/" rel="tag"># 回测指标</a>
          
            <a href="/tags/Backtrader/" rel="tag"># Backtrader</a>
          
            <a href="/tags/empyrical/" rel="tag"># empyrical</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/07/25/%E6%A0%B9%E7%AE%A1%E5%86%8D%E6%B2%BB%E7%96%97%E5%90%8E%E4%BF%AE%E5%A4%8D%EF%BC%8C%E5%8C%BB%E6%8A%80%E6%B2%9F%E9%80%9A%E3%80%82/" rel="next" title="根管再治疗后修复，医技沟通。">
                <i class="fa fa-chevron-left"></i> 根管再治疗后修复，医技沟通。
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/07/29/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B081%E2%80%94%E2%80%94%E5%AE%9E%E7%8E%B0%E9%87%8F%E5%8C%96%E4%BA%A4%E6%98%93%E7%BB%8F%E5%85%B8%E7%AD%96%E7%95%A5-%E5%B8%83%E6%9E%97%E5%B8%A6%E7%AD%96%E7%95%A5/" rel="prev" title="量化投资学习笔记81——实现量化交易经典策略:布林带策略">
                量化投资学习笔记81——实现量化交易经典策略:布林带策略 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTA2Mi8xNzU4Nw=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%20%7C%7C%20archive">
              
                  <span class="site-state-item-count">452</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">29</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">544</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">本站版权归赵瑜敏所有，如欲转载请与本人联系。</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">1225.8k</span>
  
</div>









<div>
  <script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1275447216'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s11.cnzz.com/z_stat.php%3Fid%3D1275447216%26online%3D1%26show%3Dline' type='text/javascript'%3E%3C/script%3E"));</script>
</div>

        







  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1275447216&web_id=1275447216" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  

  

  

  
</body>
</html>
